//
//  RealTimeTrainModel.m
//  CoolTennisBall
//
//  Created by Coollang on 16/7/29.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "RealTimeTrainModel.h"
#import "ChartItem.h"
#import "NSDate+FormateString.h"
#import "NSString+Extension.h"

@interface RealTimeTrainModel ()

@property (nonatomic, assign)NSInteger foreHandHitBallNumber;//正手总击球数
@property (nonatomic, assign)CGFloat foreHandaverageSpeed; //正手平均速率;
@property (nonatomic, assign)NSInteger backHandHitBallNumber;//反手总击球数
@property (nonatomic, assign)CGFloat backHandaverageSpeed; //反手平均速率;


@end

@implementation RealTimeTrainModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.startRealTimeStamp = 0;
        self.endRealTimeStamp = 0;
        self.faQiuTargetSpeed = 100;
        self.frontHandShangXuanTarget = @50;
        self.frontHandPingJiTarget = @50;
        self.frontHandXueQiuTarget = @50;
        self.frontHandPaiSuTargetSpeed = @50;
        self.backHandShangXuanTarget = @50;
        self.backHandPingJiTarget = @50;
        self.backHandXueQiuTarget = @50;
        self.backHandPaiSuTargetSpeed = @50;
        self.chartItemArray = [NSMutableArray array];
        
    }
    return self;
}




- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        
        _startRealTimeStamp = [aDecoder decodeDoubleForKey:@"startRealTimeStamp"];
        _endRealTimeStamp = [aDecoder decodeDoubleForKey:@"endRealTimeStamp"];
        _Frequency = [aDecoder decodeFloatForKey:@"Frequency"];
        _UploadTime = [aDecoder decodeObjectForKey:@"UploadTime"];
        _ID = [aDecoder decodeObjectForKey:@"ID"];
        
        _trainTyep = [aDecoder decodeIntegerForKey:@"trainTyep"];
        _chartItemArray = [aDecoder decodeObjectForKey:@"chartItemArray"];
        
        _faQiuTargetSpeed = [aDecoder decodeFloatForKey:@"faQiuTargetSpeed"];
        _faQiuAverageSpeed = [aDecoder decodeFloatForKey:@"faQiuAverageSpeed"];
        
        _frontHandShangXuanTarget = [aDecoder decodeObjectForKey:@"frontHandShangXuanTarget"];
        _frontHandPingJiTarget = [aDecoder decodeObjectForKey:@"frontHandPingJiTarget"];
        _frontHandXueQiuTarget = [aDecoder decodeObjectForKey:@"frontHandXueQiuTarget"];
        _frontHandPaiSuTargetSpeed = [aDecoder decodeObjectForKey:@"frontHandPaiSuTargetSpeed"];
        self.backHandShangXuanTarget = [aDecoder decodeObjectForKey:@"backHandShangXuanTarget"];
        self.backHandPingJiTarget = [aDecoder decodeObjectForKey:@"backHandPingJiTarget"];
        self.backHandXueQiuTarget = [aDecoder decodeObjectForKey:@"backHandXueQiuTarget"];
        self.backHandPaiSuTargetSpeed = [aDecoder decodeObjectForKey:@"backHandPaiSuTargetSpeed"];
        
        self.foreHandHitBallNumber = [aDecoder decodeIntegerForKey:@"foreHandHitBallNumber"];
        self.foreHandaverageSpeed = [aDecoder decodeFloatForKey:@"foreHandaverageSpeed"];
        self.backHandHitBallNumber = [aDecoder decodeIntegerForKey:@"BackHandHitBallNumber"];
        self.backHandaverageSpeed = [aDecoder decodeFloatForKey:@"backHandaverageSpeed"];
        
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeDouble:self.startRealTimeStamp forKey:@"startRealTimeStamp"];
    
    [aCoder encodeDouble:self.endRealTimeStamp forKey:@"endRealTimeStamp"];

    [aCoder encodeFloat: self.Frequency forKey:@"Frequency"];
    [aCoder encodeObject:self.UploadTime forKey:@"UploadTime"];
    [aCoder encodeObject:self.ID forKey:@"ID"];
    
    [aCoder encodeInteger:self.trainTyep forKey:@"trainTyep"];
    [aCoder encodeFloat:self.faQiuTargetSpeed forKey:@"faQiuTargetSpeed"];
       [aCoder encodeFloat:self.faQiuAverageSpeed forKey:@"faQiuAverageSpeed"];
    [aCoder encodeObject:self.chartItemArray forKey:@"chartItemArray"];
    
    [aCoder encodeObject:self.frontHandShangXuanTarget forKey:@"frontHandShangXuanTarget"];
    [aCoder encodeObject:self.frontHandPingJiTarget forKey:@"frontHandPingJiTarget"];
    [aCoder encodeObject:self.frontHandXueQiuTarget forKey:@"frontHandXueQiuTarget"];
    [aCoder encodeObject:self.frontHandPaiSuTargetSpeed forKey:@"frontHandPaiSuTargetSpeed"];
    
    [aCoder encodeObject:self.backHandShangXuanTarget forKey:@"backHandShangXuanTarget"];
    [aCoder encodeObject:self.backHandPingJiTarget forKey:@"backHandPingJiTarget"];
    [aCoder encodeObject:self.backHandXueQiuTarget forKey:@"backHandXueQiuTarget"];
    [aCoder encodeObject:self.backHandPaiSuTargetSpeed forKey:@"backHandPaiSuTargetSpeed"];
    
    [aCoder encodeInteger:self.foreHandHitBallNumber forKey:@"foreHandHitBallNumber"];
    [aCoder encodeFloat:self.foreHandaverageSpeed forKey:@"foreHandaverageSpeed"];
    [aCoder encodeInteger:self.backHandHitBallNumber forKey:@"BackHandHitBallNumber"];
    [aCoder encodeFloat:self.backHandaverageSpeed forKey:@"backHandaverageSpeed"];
}
- (NSString *)monthAndDay {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:NSLocalizedString(@"MM/dd", nil)];
    NSDate *date = [NSDate dateWithUnixTimeStamp:self.startRealTimeStamp];
    return [dateFormatter stringFromDate:date];
}

- (NSString *)yearAndMonthAndDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [NSDate dateWithUnixTimeStamp:self.startRealTimeStamp];
    return [dateFormatter stringFromDate:date];
}

- (NSString *)hourAndMinute {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSDate *date = [NSDate dateWithUnixTimeStamp:self.startRealTimeStamp];
    return [dateFormatter stringFromDate:date];
}



- (NSDate *)date
{
    return [NSDate dateWithUnixTimeStamp:self.startRealTimeStamp];
}

- (NSMutableArray<ChartItem *> *)chartItemArray {
    if (_chartItemArray == nil) {
        _chartItemArray = [NSMutableArray array];
    }
    return _chartItemArray;
}

- (NSString *)trainTimeLong {
    
    NSTimeInterval spacing = [[NSDate dateWithUnixTimeStamp:self.endRealTimeStamp] timeIntervalSinceDate:[self date]];
    
    if (spacing < 0) {
        spacing = 0;
    }
    
    return [NSString stringWithFormat:@"%0.f",spacing / 60.0];
}
/**
 *  发球平均速度
 */
- (CGFloat)averageValue {
   
    if (self.trainTyep != RealTimeTrainFQ || self.chartItemArray.count <= 0) {
       return 0;
    }
    
    __block CGFloat totalSpeed = 0;
    __block NSInteger number = 0;
    [self.chartItemArray enumerateObjectsUsingBlock:^(ChartItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.poseType == SportPoseTypeFaQiu || obj.poseType == SportPoseTypeKouSha) {
            totalSpeed += obj.forecastSpeed;
            number++;
        }

    }];
    
    return totalSpeed / number;
}



#pragma Mark - 计算正反手训练的部分数据

- (void)disposeForeHandData:(void(^)(NSDictionary *foreHandData))foreHand  BackHandData:(void(^)(NSDictionary *backHandData))backhand {
    
    if (self.trainTyep != RealTimeTrainHB || self.chartItemArray.count <= 0) {
        return;
    }
    
    if (self.foreHandaverageSpeed <= 0 && self.backHandaverageSpeed <= 0) {
        [self disPoseTrainData];
    }
    
    if (foreHand != nil) {
        foreHand(@{
                   ForeHandHitBallNumber:@(self.foreHandHitBallNumber),
                   ForeHandaverageSpeed: @(self.foreHandaverageSpeed)
                   });
        
    }
    if (backhand != nil) {
        backhand(
                 @{
                   BackHandHitBallNumber:@(self.backHandHitBallNumber),
                   BackHandaverageSpeed: @(self.backHandaverageSpeed),
                   }
                 );
    }
    
    
}



- (void)disPoseTrainData {
    
    __weak typeof(self) weakSelf = self;
    __block CGFloat foreHandTotalSpeed = 0;
    __block CGFloat backHandTotalSpeed = 0;
    
    
    [self.chartItemArray enumerateObjectsUsingBlock:^(ChartItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        /*  HandDirectionTypeForeward,   // 正手
         HandDirectionTypeBackward   // 反手*/
        
        if (obj.poseType == SportPoseTypeXueQiu || obj.poseType == SportPoseTypeXuanQiu || obj.poseType == SportPoseTypePingJi) {
            
            switch (obj.handDirectionType) {
                case HandDirectionTypeForeward:
                    weakSelf.foreHandHitBallNumber++;
                    foreHandTotalSpeed += obj.maxSpeed.floatValue;
                    
                    break;
                case HandDirectionTypeBackward:
                    weakSelf.backHandHitBallNumber++;
                    backHandTotalSpeed += obj.maxSpeed.floatValue;
                    break;
                    
                default:
                    break;
            }

        }
    }];
    
    //    2.计算平均速度
    if (foreHandTotalSpeed > 0 && self.foreHandHitBallNumber > 0) {
        
        _foreHandaverageSpeed = foreHandTotalSpeed /self.foreHandHitBallNumber;
    }else {
        _foreHandaverageSpeed = 0;
    }
    
    if (backHandTotalSpeed > 0 && self.backHandHitBallNumber > 0) {
        
        _backHandaverageSpeed = backHandTotalSpeed /self.backHandHitBallNumber;
    }else {
        _backHandaverageSpeed = 0;
    }
    
}

// 计算完成度-- 再保存数据之前需调用此方法，不然Frequency没值，网络请求的不用调用
- (void)calculateCopleteSituation {
    
    __block NSInteger foreHandShangXuanNum = 0;
     __block NSInteger foreHandPingJiNum = 0;
     __block NSInteger foreHandXueQiuNum = 0;
    
     __block NSInteger backHandShangXuanNum = 0;
     __block NSInteger backHandPingJiNum = 0;
     __block NSInteger backHandXueQiuNum = 0;
    
    [self.chartItemArray enumerateObjectsUsingBlock:^(ChartItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        switch (obj.poseType) {
            case SportPoseTypeXueQiu://削球
                if (obj.maxSpeed.floatValue >= [self.frontHandPaiSuTargetSpeed floatValue]) {
                    
                    obj.handDirectionType == HandDirectionTypeForeward ? foreHandXueQiuNum++ : backHandXueQiuNum++;
                }
                break;
            case SportPoseTypeXuanQiu: // 上旋
                if (obj.maxSpeed.floatValue >= [self.frontHandPaiSuTargetSpeed floatValue]) {
                    
                   obj.handDirectionType == HandDirectionTypeForeward ? foreHandShangXuanNum++ : backHandShangXuanNum++;
                }
                break;
            case SportPoseTypePingJi://平击
                if (obj.maxSpeed.floatValue >= [self.frontHandPaiSuTargetSpeed floatValue]) {
                    obj.handDirectionType == HandDirectionTypeForeward ? foreHandPingJiNum++ : backHandPingJiNum++;
                }
                break;
            default:
                break;
        }
        
    }];
    
    
    CGFloat case1 = foreHandShangXuanNum / [self.frontHandShangXuanTarget floatValue];
    CGFloat case2 = foreHandPingJiNum / [self.frontHandPingJiTarget floatValue];
    CGFloat case3 = foreHandXueQiuNum / [self.frontHandXueQiuTarget floatValue];
    CGFloat case4 = backHandShangXuanNum / [self.backHandShangXuanTarget floatValue];
    CGFloat case5 = backHandPingJiNum / [self.backHandPingJiTarget floatValue];
    CGFloat case6 = backHandXueQiuNum / [self.backHandXueQiuTarget floatValue];
    
    
    NSArray *caseArray = @[@(case1),@(case2),@(case3),@(case4),@(case5),@(case6)];
    
    NSNumber *complete = [caseArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]]].lastObject;
    /*
     [ 0,0.6 ) ——较差 [ 0.6 , 0.8 )——及格 [ 0.8 , 0.9 )——良好 [ 0.9, 1 ]——优秀
     */
    CGFloat maxCase = complete.floatValue;
    
    self.Frequency = maxCase;
    
}

- (instancetype)initWithGetNetLoadDataDict:(NSDictionary *)dict trainType:(RealTimeTrainType)type{
    
    self = [self init];
    
    if (self) {
        self.startRealTimeStamp = [dict[@"StartTime"] longLongValue];
        self.endRealTimeStamp = [dict[@"EndTime"] longLongValue];
        self.trainTyep = type;
        self.UploadTime = dict[@"UploadTime"];
        self.ID = dict[@"ID"];
        
        if (type == RealTimeTrainHB) {
            self.Frequency = [dict[@"Frequency"] floatValue];
            self.frontHandPaiSuTargetSpeed = dict[@"ForceTargetTimes"];
            self.backHandPaiSuTargetSpeed = dict[@"BackTargetTimes"];
            
            if ([self hBchartItemArray:dict[@"Detail"]]) {
                [self.chartItemArray addObjectsFromArray:[self hBchartItemArray:dict[@"Detail"]]];
            }
            
            
        }else {
            self.faQiuTargetSpeed = [dict[@"TargetSpeed"] floatValue];
            if ([self fQchartItemArray:dict[@"Detail"]]) {
                [self.chartItemArray addObjectsFromArray:[self fQchartItemArray:dict[@"Detail"]]];
            }
        }
    }
    
    
    return self;
}

- (NSArray <ChartItem *>*)hBchartItemArray:(NSArray *)detail {
    
    NSMutableArray *arrM = [NSMutableArray array];
    
    if ([detail isKindOfClass:[NSString class]]) {
        
        detail = [NSString dictionaryWithJsonString:(NSString *)detail];
        
    }
    
    if ([detail isKindOfClass:[NSArray class]]) {
        [detail enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ChartItem *item = [[ChartItem alloc] init];
            
            /*  "T" : "3",
             "F" : "0",
             "D" : "0",
             "S" : "106"*/
            // json 转字典
            if ([obj isKindOfClass:[NSString class]]) {
                NSLog(@"%@",obj);
                obj = [NSString dictionaryWithJsonString: (NSString *)obj];
                
            }
            
            item.poseType = [obj[@"T"] integerValue];
            item.handDirectionType = [obj[@"F"] integerValue];
            item.maxSpeed = obj[@"S"];
            item.unixTimeStamp = obj[@"D"];
            [arrM addObject:item];
            
        }];
    }
   
    return arrM.mutableCopy;
    
}

- (NSArray <ChartItem *>*)fQchartItemArray:(NSArray *)detail {
    NSMutableArray *arrM = [NSMutableArray array];
    
    if ([detail isKindOfClass:[NSString class]]) {
        
        detail = [NSString dictionaryWithJsonString:(NSString *)detail];
        
    }
    if ([detail isKindOfClass:[NSArray class]]) {
        [detail enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj isKindOfClass:[NSString class]]) {
                
                obj = [NSString dictionaryWithJsonString: (NSString *)obj];
                
            }
            ChartItem *item = [[ChartItem alloc] init];
            item.poseType = [obj[@"T"] integerValue];
            item.maxSpeed = obj[@"S"];
            item.unixTimeStamp = obj[@"D"];
            
            [arrM addObject:item];
        }];
    }
    
    return arrM.copy;
}


 NSString * const ForeHandHitBallNumber = @"ForeHandHitBallNumber";
 NSString * const ForeHandaverageSpeed = @"ForeHandaverageSpeed";

 NSString * const BackHandHitBallNumber = @"BackHandHitBallNumber";
 NSString * const BackHandaverageSpeed = @"BackHandaverageSpeed";


@end


